package com.ramos.kuaixiao.shops.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.MenuAdapter;
import com.ramos.kuaixiao.adapter.ParentAdapter;
import com.ramos.kuaixiao.adapter.ProductAdapter;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.ShopNew;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.ui.BrandInfoActivity;
import com.ramos.kuaixiao.ui.CaptureActivity;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class MallProductFragment extends Fragment implements OnClickListener {
    private static String TAG = "MallProductFragment";
    private Context mContext;
    private View mView;
    public final static int SCANNIN_GREQUEST_CODE = 0xb1;

    private List<String> myTypeList = new ArrayList<>();
    private List<ShopTypeBean.ShopType> shopTypeList = new ArrayList<>();
    private List<ShopTypeBean.ShopType.Type> typeList = new ArrayList<>();
    private ListView lv_brand;
    private ExpandableListView lv_brand_child;

    private MenuAdapter myMenuAdapter;
    private ParentAdapter myParentAdapter;

    private ImageView saoyisao;
    private boolean mIsSelected = false;
    private LinearLayout ll_brand;
    private LinearLayout ll_unfinished_none;
    private RelativeLayout rl_result;
    TextView tv_search_result;
    ImageButton ib_sift_goods;
    private ProductAdapter mResutAdapter;
    private ListView recListView;
    private List<ShopNew> shopList = new ArrayList<>();

    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    public final static int DETAIL_SUCCESS = 200;
    public final static int DETAIL_FAIL = 201;
    Customer mCustomer;
    private CommonLoading loading;
    SearchView searchview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        container = (ViewGroup) mView.getParent();
        if (container != null) {
            container.removeView(mView);
        }
        return mView;
    }

    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        mContext = getActivity();
        mView = LayoutInflater.from(mContext).inflate(R.layout.fragment_product, null);
        initView();
        if (App.mIsLocalData && !StringUtil.isEmpty(App.SHOP_RESULT)) {
            initLocal();
        } else {
            initShopOL();
        }
    }

    private void initLocal() {
        sendMessagea(UPLOAD_SUCCESS, App.SHOP_RESULT);
    }

    private void initView() {
        ll_unfinished_none = (LinearLayout) mView.findViewById(R.id.ll_unfinished_none);

        saoyisao = (ImageView) mView.findViewById(R.id.saoyisao);
        saoyisao.setBackgroundColor(Color.TRANSPARENT);
        saoyisao.setOnClickListener(this);

        //品牌页面
        ll_brand = (LinearLayout) mView.findViewById(R.id.ll_brand);
        rl_result = (RelativeLayout) mView.findViewById(R.id.rl_result);
        //显示品牌列表
        showBrand();

        searchview = (SearchView) mView.findViewById(R.id.searchview);
        int id = searchview.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchview.findViewById(id);
        textView.setTextSize(14);//字体、提示字体大小
        searchview.setQueryHint("搜索商品");
        searchview.setIconified(false);
        searchview.setIconifiedByDefault(false);
        int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView magImage = (ImageView) searchview.findViewById(magId);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
        Class<?> c = searchview.getClass();
        try {
            Field f = c.getDeclaredField("mSearchPlate");//通过反射，获得类对象的一个属性对象
            f.setAccessible(true);//设置此私有属性是可访问的
            View v = (View) f.get(searchview);//获得属性的值
            v.setBackgroundColor(Color.TRANSPARENT);//设置此view的背景
        } catch (Exception e) {
            e.printStackTrace();
        }
        searchview.clearFocus();

        //查询结果
        recListView = (ListView) mView.findViewById(R.id.recListView);
        recListView.setTextFilterEnabled(true);

        tv_search_result = (TextView) mView.findViewById(R.id.tv_search_result);
        ib_sift_goods = (ImageButton) mView.findViewById(R.id.ib_sift_goods);
        ib_sift_goods.setOnClickListener(this);
        recListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShopTypeBean.ShopType.ProductInfo brand = (ShopTypeBean.ShopType.ProductInfo) mResutAdapter.getItem(position);
                Intent intent = new Intent(mContext, BrandInfoActivity.class);
                intent.putExtra("brand", brand);
                intent.putExtra("customer", mCustomer);
                startActivity(intent);
            }
        });
    }

    private void showBrand() {
        lv_brand = (ListView) mView.findViewById(R.id.lv_brand);
        lv_brand_child = (ExpandableListView) mView.findViewById(R.id.lv_brand_child);
        myMenuAdapter = new MenuAdapter(mContext, myTypeList);
        lv_brand.setAdapter(myMenuAdapter);

        myParentAdapter = new ParentAdapter(mContext, typeList);
        lv_brand_child.setAdapter(myParentAdapter);
        lv_brand_child.setGroupIndicator(null);
        lv_brand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                myMenuAdapter.setSelectItem(position);
                myMenuAdapter.notifyDataSetInvalidated();
                myParentAdapter.refresh(null);
                searchview.clearFocus();
                getParentData(shopList.get(position).getBrandId());
            }
        });

        lv_brand_child.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                boolean groupExpanded = parent.isGroupExpanded(groupPosition);
                Log.d(TAG, "groupExpanded " + groupExpanded);
                return false; // 默认为false，设为true时，点击事件不会展开Group
            }
        });

        lv_brand_child.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                ShopTypeBean.ShopType.Product type = myParentAdapter.getChild(groupPosition, childPosition);
                List<ShopTypeBean.ShopType.ProductInfo> productList = type.getProductInfoNameList();
                searchType(productList);
                return false;
            }
        });
    }

    private void searchType(final List<ShopTypeBean.ShopType.ProductInfo> type) {
        mIsSelected = true;
        if (type == null) {
            tv_search_result.setText("0" + this.getResources().getString(R.string.shop_result));
        } else {
            tv_search_result.setText(type.size() + this.getResources().getString(R.string.shop_result));
        }
        ll_brand.setVisibility(View.GONE);
        rl_result.setVisibility(View.VISIBLE);
        recListView.setVisibility(View.VISIBLE);
        //mResutAdapter = new ProductAdapter(getActivity(), type);
        recListView.setAdapter(mResutAdapter);
        Product product = new Product(type);
        product.executeOnExecutor(Executors.newCachedThreadPool());
        mResutAdapter.setUpdateCarListener(new UpdateListener());
        searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onQueryTextChange(String queryText) {
                if (StringUtil.isEmpty(queryText)) {
                    mResutAdapter.getFilter().filter(null);
                    tv_search_result.setText(type.size() + mContext.getResources().getString(R.string.shop_result));
                } else {
                    Log.d(TAG, "onQueryTextChange " + queryText);
                    mResutAdapter.getFilter().filter(queryText);
                }
                return true;
            }
        });
    }

    class Product extends AsyncTask<String, String, String> {
        List<ShopTypeBean.ShopType.ProductInfo> list;

        public Product(List<ShopTypeBean.ShopType.ProductInfo> type) {
            list = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < list.size(); i++) {
                    ShopTypeBean.ShopType.ProductInfo productInfo = list.get(i);
                    String imgURL = Utils.showImg(productInfo.getProductInfoId(), productInfo.getProductBarCode());
                    if (!StringUtil.isEmpty(imgURL)) {
                        productInfo.setIconUrl(imgURL);
                    }
                    Log.d("Product", "doInBackground " + i + " " + imgURL);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Log.d("Product", "onPostExecute " + list.size());
            mResutAdapter.refresh(list);
        }
    }


    class UpdateListener implements ProductAdapter.UpdateCarListener {
        @Override
        public void update(int num, List<ShopTypeBean.ShopType.ProductInfo> tasklist) {
            tv_search_result.setText(num + mContext.getResources().getString(R.string.shop_result));
        }
    }

    private void initShopNew(String s) {
        JSONObject jsonObejct = JSONObject.parseObject(s);
        JSONObject data = jsonObejct.getJSONObject("data");
        shopList = JSONArray.parseArray(data.getJSONArray("rows").toString(), ShopNew.class);
        for (int i = 0; i < shopList.size(); i++) {
            ShopNew shopType = shopList.get(i);
            myTypeList.add(shopType.getBrandName());
        }
        myMenuAdapter.notifyDataSetChanged();
        getParentData(shopList.get(0).getBrandId());
    }

    private void getParentData(String brandId) {
        try {
            String url = NetUtils.PRODUCT_INFO_DETAIL;
            String path = url + SharedPreference.getPreferString("dealer") + "&brandId=" + brandId
                    +"&userId=" + SharedPreference.getPreferString("id");
            Log.d(TAG, "getParentData:" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            loading = new CommonLoading(mContext);
            loading.setLoadText("获取数据中...");
            // 创建请求参数的封装的对象
            client.setTimeout(100000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    loading.dismiss();
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "getParentData " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            sendMessagea(DETAIL_SUCCESS, result);
                        } else {
                            sendMessagea(DETAIL_FAIL, "fail");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(DETAIL_FAIL, "fail");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    loading.dismiss();
                    sendMessagea(DETAIL_FAIL, "fail");
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            e.printStackTrace();
        }
    }

    private void initShopOL() {
        try {
            String url = NetUtils.PRODUCT_INFO_ALL;
            String path = url + SharedPreference.getPreferString("dealer") + "&userId=" + SharedPreference.getPreferString("id");
            Log.d(TAG, "MallProduct:path=" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            loading = new CommonLoading(mContext);
            loading.setLoadText("获取数据中...");
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    loading.dismiss();
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            App.SHOP_RESULT = result;
                            sendMessagea(UPLOAD_SUCCESS, result);
                        } else {
                            sendMessagea(UPLOAD_FAIL, "fail");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(UPLOAD_FAIL, "fail");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL, "fail");
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    initShopNew(msg.obj.toString());
                    break;
                case UPLOAD_FAIL:
                    Log.d(TAG, "result fail");
                    ToastUtils.show("获取数据失败！");
                    break;
                case DETAIL_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    loadData(msg.obj.toString());
                    break;
                case DETAIL_FAIL:
                    lv_brand_child.setVisibility(View.GONE);
                    ll_unfinished_none.setVisibility(View.VISIBLE);
                    ToastUtils.show("获取数据失败！");
                    break;

                default:
                    break;
            }
        }
    };

    private void loadData(String s) {
        shopTypeList.clear();
        JSONObject jsonObejct = JSONObject.parseObject(s);
        JSONObject data = jsonObejct.getJSONObject("data");
        ShopTypeBean shopTypeBean = JSONObject.parseObject(data.toString(), ShopTypeBean.class);
        for (int i = 0; i < shopTypeBean.getBrandList().size(); i++) {
            ShopTypeBean.ShopType shopType = shopTypeBean.getBrandList().get(i);
            shopTypeList.add(shopType);
        }
        if (shopTypeList != null && shopTypeList.size() > 0) {
            lv_brand_child.setVisibility(View.VISIBLE);
            ll_unfinished_none.setVisibility(View.GONE);
            myParentAdapter = new ParentAdapter(mContext, shopTypeList.get(0).getTypeGroupList());
            lv_brand_child.setAdapter(myParentAdapter);
            if (shopTypeList.size() > 0) {
                lv_brand_child.expandGroup(0);
            }
        } else {
            myParentAdapter.refresh(null);
            lv_brand_child.setVisibility(View.GONE);
            ll_unfinished_none.setVisibility(View.VISIBLE);
        }
    }

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saoyisao:
                if (mIsSelected) {
                    Intent intent = new Intent();
                    intent.setClass(mContext, CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                } else {
                    ToastUtils.show("暂无商品，无法扫描！");
                }
                break;
            case R.id.ib_sift_goods:
                showList();
                break;
            default:
                break;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == SCANNIN_GREQUEST_CODE) {
                Log.d(TAG, "onActivityResult " + data.getExtras().getString("scan_code"));
                searchview.setQuery(data.getExtras().getString("scan_code"), true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showList() {
        ll_brand.setVisibility(View.VISIBLE);
        rl_result.setVisibility(View.GONE);
        recListView.setVisibility(View.GONE);
        mIsSelected = false;
        searchview.clearFocus();
    }
}
